//
//  UpdataImageManager.m
//  Campus
//
//  Created by Hancong on 15/1/20.
//  Copyright (c) 2015年 hzyd. All rights reserved.
//

#import "UpLoadImageManager.h"
#import "KInterFace.h"
#import "SVProgressHUD.h"
#import "HttpRequestManager.h"
#import "SDWebImageManager.h"

@implementation UpLoadImageManager

+(void)uploadImage:(UIImage *)image withCompltedBlock:(void (^)(BOOL success,NSString *urlString))block
{
    /**
     *  上传图片
     *
     */
    NSData *data = UIImageJPEGRepresentation(image, 0.1f);
    
    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KBasePath,KinterFace_uploadPics]]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //得到图片的data
    //    NSData* data;
    data = UIImageJPEGRepresentation(image, 0.1f);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    
    //    if(picFilePath){
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"files",@"currentImage.jpg"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
    //    }
    //    NSLog(@"body = %@",body);
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //    if(picFilePath){
    //将image的data加入
    [myRequestData appendData:data];
    //    }
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%ld", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    NSLog(@"Length = %ld",[myRequestData length]);
    
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    //    request set
//    [[NSUserDefaults standardUserDefaults] setObject:response[@"value"][@"token"] forKey:KUserDefaultsToken];

    NSString *cookie = [[NSUserDefaults standardUserDefaults] objectForKey:KUserDefaultsToken];
    
    [request setValue:cookie forHTTPHeaderField:@"TOKEN"];
    
    __block NSString *postImageUrl;
    [SVProgressHUD showWithStatus:@"正在获取图片..."];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        NSHTTPURLResponse *urlResponese = nil;
        NSError *error = [[NSError alloc]init];
        NSData* resultData = [NSURLConnection sendSynchronousRequest:request   returningResponse:&urlResponese error:&error];

        if (resultData) {
            NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableLeaves error:nil ];
            dispatch_async(dispatch_get_main_queue(), ^{
                if([dicData[@"code"] intValue] == 0)
                {
                    postImageUrl = [NSString stringWithFormat:@"%@",dicData[@"value"][@"files"]];
//                    _postUrl = [NSString stringWithFormat:@"%@",dicData[@"data"][0]];
                    [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:postImageUrl]];

                    __block NSString *strID;
                    NSDictionary *parameters = @{@"hash":postImageUrl
                                                 };
                    [HttpRequestManager postMethod:KinterFace_uploadOss parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                        if (success) {
                            strID = response[@"value"][@"id"];
                            if (block) {
                                block(YES,strID);
                            }
                        }else{
                            block(NO,@"");
                        }
//                        NSLog(@"%@",response);
                    }];

                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:@"上传失败"];
                        postImageUrl = @"";
                        
                        if (block) {
                            block(NO,postImageUrl);
                        }
                    });
                }
                [SVProgressHUD dismiss];
                
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:@"上传失败"];
                postImageUrl = @"";
                if (block) {
                    block(NO,postImageUrl);
                }
            });
        }
    });
}

//+ (UIImage *)fullResolutionImageFromALAsset:(ALAsset *)asset
//{
//    ALAssetRepresentation *assetRep = [asset defaultRepresentation];
//    CGImageRef imgRef = [assetRep fullResolutionImage];
//    UIImage *img = [UIImage imageWithCGImage:imgRef
//                                       scale:assetRep.scale
//                                 orientation:(UIImageOrientation)assetRep.orientation];
//    
//    return img;
//}

@end
